package com.security.control.browser.controller;

import com.security.control.core.social.support.SocialController;
import com.security.control.core.social.support.SocialUserInfo;
import com.security.control.core.support.SecurityConstants;
import com.security.control.core.support.SimpleResponseEntity;
import com.security.control.core.properties.SecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author imoot@gamil.com
 * @date 2018/12/18 0018 9:38
 */
@RestController
public class BrowserSecurityController extends SocialController {

    private Logger log = LoggerFactory.getLogger(BrowserSecurityController.class);

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
     * @param request
     * @param response
     * @return SimpleResponseEntity
     * 身份认证时，跳转到这里
     * @throws Exception
     */
    @RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)//设置返回状态码为401
    public SimpleResponseEntity requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (null != savedRequest) {
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是：" + targetUrl);
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowserProperties().getSignInUrl());
            }
        }
        return new SimpleResponseEntity("访问的服务需要身份认证，请前往登录页面");
    }

    /**
     * @param request
     * @return SocialUserInfo
     * 用户使用社交登陆账号注册或者绑定时，从session中取出第三方用户信息显示在注册或者绑定页面
     */
    @GetMapping(SecurityConstants.DEFAULT_SOCIAL_USER_INFO_URL)
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        //SpringSocial在SocialAuthenticationFilter.doAuthentication()时判断登录url不为空会把第三方用户信息放入session中
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        return buildSocialUserInfo(connection);
    }
}
